<script setup lang="ts">
import { ref, computed, onBeforeUnmount, shallowRef, reactive } from 'vue';
import { useOrderInfo } from '@/stores/orderInfo';
import userAddress from '../components/userAddress.vue';
import { useRoute, useRouter } from 'vue-router';
import { goodsBuy, shopOrderDetail } from '@/common/api/hbMarket';
import { copyHandler } from '@/utils/util';
import { showToast } from 'vant';
import { useToastLoading } from '@/composables/useToastLoading';
// import refundApply from '../components/refundApply.vue';
import { useUserInfo } from '@/stores/userInfo';
// import orderRefundAuditDialog from '../components/orderRefundAuditDialog.vue';
// import orderSendDialog from '../components/orderSendDialog.vue';

// 定义引用
// const refundApplyRef = shallowRef<InstanceType<typeof refundApply>>();
// const orderRefundAuditDialogRef = shallowRef<InstanceType<typeof orderRefundAuditDialog>>();
// const orderSendDialogRef = shallowRef<InstanceType<typeof orderSendDialog>>();

const route = useRoute();
const router = useRouter();
const orderInfo = useOrderInfo();
const userInfo = useUserInfo();

// 清除缓存
onBeforeUnmount(() => {
  orderInfo.clearOrderInfo();
});

const oid = ref(route.query?.oid || ''); // 订单编号
const subLoading = ref(false); // 提交订单加载中
const loading = ref(false); // 页面加载中
const kdInfo = reactive<{
  name: string;
  text: any;
}>({
  name: '',
  text: null,
});
const orderDetail = computed(() => orderInfo.state.info);
// 总价
const totalPrice = computed(() => Number(orderDetail.value.skuInfo?.skuprice || 0) * 100 * orderDetail.value.cnt);

// 提交订单
const onSubmit = async () => {
  if (!orderDetail.value?.shouhuoid) {
    return showToast('请选择收货地址');
  }
  console.log('orderDetail ', orderDetail.value.skuInfo?.skuid);
  subLoading.value = true;
  try {
    const res = await goodsBuy({
      ...orderDetail.value,
      pids: `${orderDetail.value.pid}:${orderDetail.value.skuInfo?.skuid}:${orderDetail.value.cnt}`,
      oid: oid.value,
    });
    const orderId = res.result.data.oid;
    router.replace('/hbMarket/orderDetail?oid=' + orderId);
    oid.value = orderId;
    getOrderDetail();
  } catch {
    /** empty */
  } finally {
    subLoading.value = false;
  }
};

const getOrderDetail = async () => {
  loading.value = true;
  try {
    const res = await shopOrderDetail({ oid: oid.value });
    console.log('订单详情: ', res.result.data);
    if (res.result.data) {
      orderInfo.setOrderInfo({
        ...res.result.data,
        skuInfo: {
          skuprice: res.result.data.price,
          skuname: res.result.data.skuname, // 规格名称
          price: res.result.data.price, // 原价
          images: res.result.data.skuimages,
        },
      });
    }
  } catch {
    /** empty */
  } finally {
    loading.value = false;
  }
};
oid.value && getOrderDetail();

useToastLoading(loading);

// 文本复制
const copyText = (text: string) => {
  const { errMsg } = copyHandler({ data: text });
  if (errMsg.indexOf('ok') > -1) {
    showToast('复制成功');
  }
  console.log(errMsg);
};

// 申请退款
// const handleRefund = (oid: string) => {
//   refundApplyRef.value?.open(oid);
// };

// 退款审核
// const handleRefundAudit = (oid: string) => {
//   orderRefundAuditDialogRef.value?.open(oid);
// };

// 订单发货
// const handleOrderSend = (oid: string) => {
//   orderSendDialogRef.value?.open(oid);
// };
</script>
<template>
  <div class="orderDetail">
    <userAddress :oid="(oid as string)" />
    <van-cell-group inset class="!mt-3" v-if="!oid">
      <van-cell title="配送方式" value="快递" />
      <!-- <van-cell title="运费合计" :value="`￥${orderDetail.freight || 0}`" /> -->
    </van-cell-group>
    <van-cell-group inset class="!mt-3">
      <van-cell>
        <template #title>
          <div class="flex items-center">
            <van-icon name="bag-o" />
            <span class="ml-1">商品信息</span>
          </div>
        </template>
        <template #label>
          <div class="flex pt-2">
            <van-image
              width="100"
              height="100"
              radius="7"
              fit="cover"
              :src="orderDetail?.skuInfo?.images ? orderDetail.skuInfo.images.split(',')[0] : ''"
            />
            <div class="flex flex-col justify-between pl-3 flex-1">
              <div class="text-black">{{ orderDetail.skuInfo?.skuname || '' }}</div>
              <div class="flex items-center justify-between">
                <span class="text-[red]">{{ orderDetail.skuInfo?.skuprice || 0 }}积分</span>
                <span>x{{ orderDetail.cnt }}</span>
              </div>
            </div>
          </div>
        </template>
      </van-cell>
    </van-cell-group>
    <van-cell-group inset class="!mt-3" v-if="oid">
      <van-cell title="订单编号" value-class="!flex-[2_2_0%]">
        <template #value>
          <div class="flex items-center justify-end">
            <span class="mr-2">{{ orderDetail.oid }}</span>
            <van-button size="mini" @click="copyText(orderDetail?.oid || '')">复制</van-button>
          </div>
        </template>
      </van-cell>
      <!-- <van-cell title="运费" :value="`￥${orderDetail.freight || 0}`" /> -->
      <van-cell title="实付款" :value="`${orderDetail.total_price || 0}积分`" />
      <van-cell title="下单时间" :value="orderDetail.crt_time" />
      <van-cell title="订单状态" value-class="!text-[red]" :value="orderDetail.status" />
    </van-cell-group>

    <van-cell-group inset class="!mt-3" v-if="kdInfo.name && kdInfo.text">
      <div class="p-2">
        <div class="text-sm p-2">{{ kdInfo.name }}</div>
        <van-steps direction="vertical" :active="0">
          <van-step v-for="(item, idx) in kdInfo.text.data" :key="idx">
            <h3>{{ item.context }}</h3>
            <p>{{ item.time }}</p>
          </van-step>
        </van-steps>
      </div>
    </van-cell-group>

    <van-submit-bar
      v-if="!oid"
      :price="totalPrice"
      button-color="#EC2D69"
      :loading="subLoading"
      :disabled="!orderDetail.shouhuoid || !orderDetail.skuInfo?.skuname"
      button-text="提交订单"
      @submit="onSubmit"
    />

    <div class="bottom-btn" v-if="false">
      <template v-if="false">
        <!-- 我买到的商品 -->
        <!-- <van-button round v-if="orderDetail.status === 1" @click.stop="handleRefund(orderDetail.oid)">
          申请退款
        </van-button> -->
      </template>
      <template v-else>
        <!-- 我卖出的商品 -->
        <!-- <van-button round v-if="orderDetail.status === 4" @click.stop="handleRefundAudit(orderDetail.oid)">
          退款审核
        </van-button> -->
        <!-- <van-button round v-if="orderDetail.status === 1" @click.stop="handleOrderSend(orderDetail.oid)">
          订单发货
        </van-button> -->
      </template>
    </div>

    <!-- 订单申请退款弹窗 -->
    <!-- <refund-apply ref="refundApplyRef" @onRefresh="getOrderDetail"></refund-apply> -->
    <!-- 订单退款审核弹窗 -->
    <!-- <orderRefundAuditDialog ref="orderRefundAuditDialogRef" @onRefresh="getOrderDetail" /> -->
    <!-- 订单发货弹窗 -->
    <!-- <orderSendDialog ref="orderSendDialogRef" @onRefresh="getOrderDetail" /> -->
  </div>
</template>
<style lang="less" scoped>
.orderDetail {
  padding-top: 10px;
  padding-bottom: 80px;
  min-height: 100%;
  background: #fafafa;
  .bottom-btn {
    position: fixed;
    width: 100%;
    bottom: 0;
    left: 0;
    display: flex;
    justify-content: flex-end;
    background: #ffffff;
    padding: 10px;
  }
}
</style>
